import { makeObservable, observable, action, computed } from 'mobx';

class appleStore {
    apples = [
        {
            id: 0,
            weight: 233,
            num:1,
            isEaten: false
        },
        {
            id: 1,
            num:2,
            weight: 235,
            isEaten: true
        },
        {
            id: 2,
            num:3,
            weight: 256,
            isEaten: false
        }
    ]
    picking = false;
    buttonText = '摘苹果';
    newAppleId = 3;
    weight = '';

    constructor (apples){
        makeObservable(this, {
            apples: observable,
            pickApple: action,
            eatApple: action,
            status: computed,
            newAppleId: observable,
            picking: observable,
            buttonText: observable
        })
    }
    get status (){
        let status = {
            appleNow: {
                quantity: 0,
                weight: 0
            },
            appleEaten: {
                quantity: 0,
                weight: 0
            }
        };
        this.apples.forEach(apple => {
            let selector = apple.isEaten ? 'appleEaten':'appleNow';
            status[selector].quantity ++;
            status[selector].weight += apple.weight;
        });
        return status;
    }
    pickApple = () => {
        if(this.picking) return;
        this.picking = true;
        this.buttonText = '正在采摘...';
        setTimeout(()=>{
            this.picking = false;
            this.buttonText = '摘苹果';
            let weight = Math.floor(200 + Math.random() * 50);
            this.apples.push({
                id: this.newAppleId++,
                weight: weight,
                num:this.apples.length,
                isEaten: false
            })
        },500)
    }
    eatApple = (appleId) => {
        let targetIndex = '';
        this.apples.forEach((apple,index)=>{
            if(apple.id === appleId){
                targetIndex = index
            }
        });
        this.apples[targetIndex].isEaten = true;
    }
    
}
export default appleStore 
